package com.easyUploader.config;

import com.easyUploader.entity.dto.UserDto;
import com.easyUploader.threadHolder.UserThreadHolder;
import com.security.domain.authority.CommonUserDetails;
import com.security.filter.FilterInterceptor;
import com.security.service.AuthenticateService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.easyUploader.entity.factory.UserFactory.USER_CONVERTER;

/**
 * @author 大忽悠
 * @create 2022/11/19 15:22
 */
@Configuration
public class WebSecurityConfig {

    @Bean("filterInterceptor-01")
    public FilterInterceptor tokenAuthFilter(AuthenticateService authenticateService) {
        return new FilterInterceptor() {
            @Override
            public void beforeSuccessAuthInvoke(HttpServletRequest request, HttpServletResponse response) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                UserDto userDto = USER_CONVERTER.toUserDto((CommonUserDetails) authentication.getPrincipal());
                UserThreadHolder.set(userDto);
            }

            @Override
            public void afterSuccessAuthInvoke(HttpServletRequest request, HttpServletResponse response) {
                UserThreadHolder.clear();
            }
        };
    }

}
